﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Bzzb.Model;
using FreeSql;
using FreeSql.Internal.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Bzzb.Controllers
{
    public class AdminController : BaseController
    {
        private readonly ILogger<AdminController> _logger;
        public AdminController(ILogger<AdminController> logger, IFreeSql fsql) : base(fsql)
        {
            this._logger = logger;
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Index([FromForm] long dpid, [FromForm] string content, [FromForm] int pageNumber = 1, [FromForm] int pageSize = 10)
        {
            ISelect<User> select = _fsql.Select<User>();
            // 根据部门ID查询出来所有用户ID
            if (dpid > 0)
            {
                List<long> uids = await _fsql.Select<DepartmentUser>().Where(dpu => dpu.Dpid == dpid).ToListAsync(dpu => dpu.Uid);
                _logger.LogInformation("部门查询的SQL：" + _fsql.Select<DepartmentUser>().Where(dpu => dpu.Dpid == dpid).ToSql(dpu => dpu.Uid));
                select.Where(u => uids.Contains(u.Id));
            }
            DynamicFilterInfo dyfilter = JsonConvert.DeserializeObject<DynamicFilterInfo>(@"
{
  'Logic' : 'Or',
  'Filters' :
  [
    {
      'Field' : 'realname',
      'Operator' : 'Contains',
      'Value' : '" + content + @"',
    },
    {
      'Field' : 'mobile',
      'Operator' : 'Contains',
      'Value' : '" + content + @"',
    }
  ]
}
");
            select.WhereDynamicFilter(dyfilter);
            List<User> users = await select.Count(out var total).Page(pageNumber, pageSize).ToListAsync();
            _logger.LogInformation("员工查询的SQL：" + select.Count(out var total1).Page(1, 20).ToSql());
            JObject jo_data = new();
            jo_data.Add("total", total);
            JArray ja_users = new();
            foreach (User user in users)
            {
                JObject jo_user = JObject.FromObject(user);
                #region 备用1
                //if (!String.IsNullOrEmpty(user.Dpids))
                //{
                //    string[] dpids = user.Dpids.Split(",");
                //    List<Department> departments = await _fsql.Select<Department>().Where(d => dpids.Contains(d.Id.ToString())).ToListAsync();
                //    jo_user.Add("dpids_name", JArray.FromObject(departments));
                //}
                //else
                //{
                //    jo_user.Add("dpids_name", new JArray());
                //}
                //if (!String.IsNullOrEmpty(user.Rids))
                //{
                //    string[] rids = user.Rids.Split(",");
                //    List<Role> roles = await _fsql.Select<Role>().Where(r => rids.Contains(r.Id.ToString())).ToListAsync();
                //    jo_user.Add("rids_name", JArray.FromObject(roles));
                //}
                //else
                //{
                //    jo_user.Add("rids_name", new JArray());
                //}
                #endregion

                #region 备用2
                // 查询出来用户所有部门
                //List<long> dpids = await _fsql.Select<DepartmentUser>().Where(dpu => dpu.Uid == user.Id).ToListAsync(dpu => dpu.Dpid);
                //if (dpids != null && dpids.Count > 0)
                //{
                //    List<string> dptNames = await _fsql.Select<Department>().Where(dpt => dpids.Contains(dpt.Id)).ToListAsync(dpt => dpt.Name);
                //    jo_user.Add("dptnames", JArray.FromObject(dptNames));
                //}
                //else
                //{
                //    jo_user.Add("dptnames", new JArray());
                //}
                //// 查询出来用户所有角色
                //List<long> rids = await _fsql.Select<RoleUser>().Where(ru => ru.Uid == user.Id).ToListAsync(ru => ru.Rid);
                //if (rids != null && rids.Count > 0)
                //{
                //    List<string> roleNames = await _fsql.Select<Role>().Where(r => rids.Contains(r.Id)).ToListAsync(r => r.Name);
                //    _logger.LogInformation("角色表查询：" + _fsql.Select<Role>().Where(r => rids.Contains(r.Id)).ToSql(r => r.Name));
                //    jo_user.Add("rolenames", JArray.FromObject(roleNames));
                //}
                //else
                //{
                //    jo_user.Add("rolenames", new JArray());
                //}
                //ja_users.Add(jo_user);
                #endregion
                // 查询出来用户所有部门
                List<long> dpids = await _fsql.Select<DepartmentUser>().Where(dpu => dpu.Uid == user.Id).ToListAsync(dpu => dpu.Dpid);
                if (dpids != null && dpids.Count > 0)
                {
                    List<Department> dptNames = await _fsql.Select<Department>().Where(dpt => dpids.Contains(dpt.Id)).ToListAsync();
                    jo_user.Add("departments", JArray.FromObject(dptNames));
                }
                else {
                    jo_user.Add("departments", new JArray());
                }
                // 查询出来用户所有角色
                List<long> rids = await _fsql.Select<RoleUser>().Where(ru => ru.Uid == user.Id).ToListAsync(ru => ru.Rid);
                if (rids != null && rids.Count > 0)
                {
                    List<Role> roleNames = await _fsql.Select<Role>().Where(r => rids.Contains(r.Id)).ToListAsync();
                    _logger.LogInformation("角色表查询：" + _fsql.Select<Role>().Where(r => rids.Contains(r.Id)).ToSql());
                    jo_user.Add("roles", JArray.FromObject(roleNames));
                }
                else
                {
                    jo_user.Add("roles", new JArray());
                }
                ja_users.Add(jo_user);
            }
            jo_data.Add("list", ja_users);
            return RenderJson(data: jo_data);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Save([FromForm] User user)
        {
            _logger.LogInformation("用户部门参数信息：" + Request.Form["dpids"]);
            if (user.Dpids?.Length == 0) {
                return RenderJson(status: "失败", message: "请选择部门", code: -1);
            }

            //if (string.IsNullOrEmpty(user.Rids))
            //{
            //    return RenderJson(status: "失败", message: "请选择角色", code: -1);
            //}

            // 判断用户是否存在
            User isExistsUser = await _fsql.Select<User>().Where(u => u.Username == user.Username).ToOneAsync();
            if (isExistsUser != null)
            {
                return RenderJson(status: "失败", message: "该用户已经存在", code: -1);
            }

            // 开启事务插入部门和角色
            long id = await _fsql.Insert(user).ExecuteIdentityAsync();
            user.Id = id;

            List<DepartmentUser> dpusers = new();
            foreach (long strdpid in user.Dpids)
            {
                dpusers.Add(new DepartmentUser { Dpid = strdpid, Uid = id });
            }

            //List<RoleUser> roleusers = new List<RoleUser>();
            //foreach (string strrid in user.Rids.Split(","))
            //{
            //    roleusers.Add(new RoleUser { Rid = long.Parse(strrid), Uid = id });
            //}
            _fsql.Transaction(() =>
            {
                // 清空当前用户所有部门，插入新的部门
                _fsql.Delete<DepartmentUser>().Where(dpu => dpu.Uid == id).ExecuteAffrows();
                int affrows = _fsql.Insert(dpusers).ExecuteAffrows();
                if (affrows < 1)
                    throw new Exception("插入部门失败");

                // 清空当前用户所有角色，插入新的角色
                //_fsql.Delete<RoleUser>().Where(ru => ru.Uid == id).ExecuteAffrows();
                //affrows = _fsql.Insert(roleusers).ExecuteAffrows();
                //if (affrows < 1)
                //    throw new Exception("插入角色失败");
            });


            return RenderJson(data: user);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Delete([FromForm] long id) {
            User user = await _fsql.Select<User>().Where(u => u.Id == id).ToOneAsync();
            if (user.Username.Equals("admin")) {
                return RenderJson(status: "failed", message: "管理员无法删除", code: -1, data: user);
            }
            int affrows = await _fsql.Delete<User>().Where(u => u.Id == id).ExecuteAffrowsAsync();
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Update([FromForm] User user) {
            int affrows = await _fsql.Update<User>().SetSourceIgnore(user, colval => colval == null).ExecuteAffrowsAsync();

            // 开启事务插入部门和角色
            List<DepartmentUser> dpusers = new();
            foreach (long strdpid in user.Dpids)
            {
                dpusers.Add(new DepartmentUser { Dpid = strdpid, Uid = user.Id });
            }

            //List<RoleUser> roleusers = new List<RoleUser>();
            //foreach (string strrid in user.Rids.Split(","))
            //{
            //    roleusers.Add(new RoleUser { Rid = long.Parse(strrid), Uid = user.Id });
            //}
            _fsql.Transaction(() =>
            {
                // 清空当前用户所有部门，插入新的部门
                _fsql.Delete<DepartmentUser>().Where(dpu => dpu.Uid == user.Id).ExecuteAffrows();
                int affrows = _fsql.Insert(dpusers).ExecuteAffrows();
                if (affrows < 1)
                    throw new Exception("插入部门失败");

                // 清空当前用户所有角色，插入新的角色
                //_fsql.Delete<RoleUser>().Where(ru => ru.Uid == user.Id).ExecuteAffrows();
                //affrows = _fsql.Insert(roleusers).ExecuteAffrows();
                //if (affrows < 1)
                //    throw new Exception("插入角色失败");
            });

            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Show([FromForm] long id) {
            User user = await _fsql.Select<User>().Where(u => u.Id == id).ToOneAsync();
            JObject jo_user = JObject.FromObject(user);
            #region 将来可能用到
            //// 查询出来用户所有部门
            //List<long> dpids = await _fsql.Select<DptUser>().Where(dpu => dpu.Uid == user.Id).ToListAsync(dpu => dpu.Dptid);
            //if (dpids != null && dpids.Count > 0)
            //{
            //    List<string> dptNames = await _fsql.Select<Department>().Where(dpt => dpids.Contains(dpt.Id)).ToListAsync(dpt => dpt.Name);
            //    jo_user.Add("dptnames", JArray.FromObject(dptNames));
            //}
            //else
            //{
            //    jo_user.Add("dptnames", new JArray());
            //}
            //// 查询出来用户所有角色
            //List<long> rids = await _fsql.Select<RoleUser>().Where(ru => ru.Uid == user.Id).ToListAsync(ru => ru.Rid);
            //if (rids != null && rids.Count > 0)
            //{
            //    List<string> roleNames = await _fsql.Select<Role>().Where(r => rids.Contains(r.Id)).ToListAsync(r => r.Name);
            //    _logger.LogInformation("角色表查询：" + _fsql.Select<Role>().Where(r => rids.Contains(r.Id)).ToSql(r => r.Name));
            //    jo_user.Add("rolenames", JArray.FromObject(roleNames));
            //}
            //else
            //{
            //    jo_user.Add("rolenames", new JArray());
            //}
            #endregion

            #region 备用2
            // 查询出来用户所有部门
            //List<long> dpids = await _fsql.Select<DepartmentUser>().Where(dpu => dpu.Uid == user.Id).ToListAsync(dpu => dpu.Dpid);
            //jo_user.Add("dpids", JArray.FromObject(dpids));
            //// 查询出来用户所有角色
            //List<long> rids = await _fsql.Select<RoleUser>().Where(ru => ru.Uid == user.Id).ToListAsync(ru => ru.Rid);
            //jo_user.Add("rids", JArray.FromObject(rids));
            #endregion

            // 查询出来用户所有部门
            List<long> dpids = await _fsql.Select<DepartmentUser>().Where(dpu => dpu.Uid == user.Id).ToListAsync(dpu => dpu.Dpid);
            if (dpids != null && dpids.Count > 0)
            {
                List<Department> dptNames = await _fsql.Select<Department>().Where(dpt => dpids.Contains(dpt.Id)).ToListAsync();
                jo_user.Add("departments", JArray.FromObject(dptNames));
            }
            else
            {
                jo_user.Add("departments", new JArray());
            }
            // 查询出来用户所有角色
            List<long> rids = await _fsql.Select<RoleUser>().Where(ru => ru.Uid == user.Id).ToListAsync(ru => ru.Rid);
            if (rids != null && rids.Count > 0)
            {
                List<Role> roleNames = await _fsql.Select<Role>().Where(r => rids.Contains(r.Id)).ToListAsync();
                _logger.LogInformation("角色表查询：" + _fsql.Select<Role>().Where(r => rids.Contains(r.Id)).ToSql());
                jo_user.Add("roles", JArray.FromObject(roleNames));
            }
            else
            {
                jo_user.Add("roles", new JArray());
            }

            return RenderJson(data: jo_user);
        }
    }
}
